﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Churchtoolkit.Utils.EmailProvider;
using Churchtoolkit.DataAccess.Repositories;
using System.Net.Mail;
using System.Threading;
using System.Net;

namespace Churchtoolkit.Web.Shell.Services
{
    public class EmailService : IEmailProvider
    {
        private EmailsRepository _emailRepository;
        public EmailService(EmailsRepository emailRepository)
        {
            _emailRepository = emailRepository;
        }

        #region Implementation of IEmailProvider

        public void SendMail(string emailAddress, string emailTemplateCode, params object[] arguments)
        {
            var mailTemplate = _emailRepository.Find(email => email.Code = emailTemplateCode, null, 0, 1).Single();
            //------------------------------------------------------------------------------------------------------
            ThreadPool.QueueUserWorkItem((dummy) =>
                {
                    MailMessage msg = new MailMessage();
                    msg.To.Add(emailAddress);
                    msg.Subject = mailTemplate.Subject;
                    msg.IsBodyHtml = true;
                    msg.Body = string.Format(mailTemplate.Template, arguments);
                    SmtpClient smtp = new SmtpClient();
                    smtp.EnableSsl = true;
                    smtp.Send(msg);
                });
        }
        #endregion
    }
}
